/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package construtora.limiar.servlet;

import construtora.limiar.constants.Operacoes;
import construtora.limiar.dao.UsuarioDAO;
import construtora.limiar.dao.generic.DAOEngine;
import construtora.limiar.mensagens.Message;
import construtora.limiar.models.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author michel
 */
@WebServlet(name = "AutenticarSlt", urlPatterns = {"/AutenticarSlt"})
public class AutenticarSlt extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    //private static final long serialVersionUID = 1L;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operacao = request.getParameter("operacao");
        RequestDispatcher rd = null;
        if (operacao.equals(Operacoes.LOGIN)) {
            login(request, response);
        }
        if (operacao.equals(Operacoes.LOGOUT)) {
            logout(request, response);
        }
    }
    
    private void logout(HttpServletRequest request, HttpServletResponse response) {
        getServletContext().removeAttribute("funcionario");
        try {
            response.sendRedirect("login.jsp");
        } catch (IOException e) {
            tratarErro(response, e);
        }
    }
    
    private void login(HttpServletRequest request, HttpServletResponse response) {
        String nome = request.getParameter("nome");
        String senha = request.getParameter("senha");
        DAOEngine dao = new DAOEngine(nome, senha);
        try{
            if(dao.openConnnection()){
                //Precisa de um jeito de identificar o usuario e sua role
                //
                //getServletContext().setAttribute("usuario", usuario.get(0));
                response.sendRedirect("home.jsp");
            }else{
                //Message.setLastInfo("Apelido ou senha inválidos!");
                //response.sendRedirect("index.jsp");
                
                String msg = "Apelido ou senha inválidos!";
                request.setAttribute("msg",msg);
                //rd = request.getRequestDispatcher("/index.jsp");
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                rd.forward(request, response);
            } 
        }catch(Exception e) {
            Message.setLastException(e.getMessage());
            tratarErro(response, e);
        }   
        /*
        UsuarioDAO dao = new UsuarioDAO();
        try {
            List<Usuario> usuario = (List<Usuario>) dao.fetchAll("apelido = '"
            + apelido + "' and senha ='" + senha + "'", null, null, null);
            if (usuario != null && usuario.size() == 1) {
                getServletContext().setAttribute("usuario", usuario.get(0));
                response.sendRedirect("admin.jsp");
            } else {
                Message.setLastInfo("Apelido ou senha inválidos!");
                response.sendRedirect("login.jsp");
            }
        } catch (Exception e) {
            Message.setLastException(e.getMessage());
            tratarErro(response, e);
        }
        */
    }
    
    
    private void tratarErro(HttpServletResponse response, Exception e) {
        try {
            response.sendRedirect("erro.jsp?mensagem=" + e.getMessage());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }




    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
